<?php
/**
 * Created by PhpStorm.
 * User: chang
 * Date: 2019/3/6
 * Time: 15:27
 */

namespace App\Http\Services;


use App\Http\Model\Hint;
use App\Http\Model\User;
use App\Http\Model\Popularize;
use Detection\MobileDetect;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class PopularizeServices extends CommonServices
{
    private $referrer;
    private $systemService;
    
    public function __construct(User $user, Popularize $referrer, SystemServices $systemService)
    {
        parent::__construct();

        $this->referrer = $referrer;
        $this->systemService = $systemService;
    }
    
    /**
     * 写入缓存
     * @param $key
     * @param $code
     */
    public function set_recommend_code($key, $code)
    {
        $this->referrer->set_recommend_code($key, $code);
    }
    
    /**
     * 根据code绑定用户与推荐人
     * @param int $user_id
     * @return bool
     */
    public function check_recommend_code(int $user_id)
    {
        $redis_field = $this->get_client_os_version();
        if(null === $redis_field) return false;
        
        $code = $this->referrer->get_recommend_code($redis_field);
        
        if(!$code) return false;
        
        //获取推荐人id
        $bid = decode($code);
        if($user_id === $bid) return false;
        
        $res = $this->referrer->create_relation($user_id, $bid);
        if($res > 0) {
            return $this->referrer->remove_recommend_code($redis_field);
        }
        return false;
    }
    
    /**
     * @return string|null os version # 手机型号
     */
    private function get_client_os_version(){
        $user_agent = $_SERVER["HTTP_USER_AGENT"] ?? '';
        if(!empty($user_agent)){
            $user_agent = explode(";",$user_agent);
            
            $os = strtolower($user_agent[2]);
            $version = strtolower($user_agent[3]);
            $device = strtolower($user_agent[4]);
            
            $pattern = "/[^a-zA-Z0-9]/i";
            $os = preg_replace($pattern,"", $os);
            $device = preg_replace($pattern, "" ,$device);
            
            $key = $os . "#" .$version. "#". $device;
            return $key;
        }
        return null;
    }
}